import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'
import store from '@/store'

export const routes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index'),
    hidden: true // 控制当前路由对象是否在侧边栏显示一项
  },
  {
    path: '/',
    component: Layout,
    redirect: '/workbench'
  },
  {
    path: '/workbench',
    component: Layout,
    children: [{
      path: '',
      component: () => import('@/views/Workbench/index'),
      meta: { title: '工作台', icon: 'el-icon-data-board' }
    }]
  },
  { // 行车管理-月卡管理-新增月卡
    path: '/add-card',
    component: () => import('@/views/Car/CarCard/addCard.vue')
  },
  { // 园区管理-企业管理-新增企业
    path: '/add-ep',
    component: () => import('@/views/Park/Enterprise/add-ep.vue')
  }, // 园区管理-企业管理-查看企业详情
  {
    path: '/ep-detail',
    component: () => import('@/views/Park/Enterprise/detail.vue')
  }, {
    // 系统管理-角色管理-新增角色
    path: '/add-role',
    component: () => import('@/views/System/Role/add-role.vue')
  }, // 行车管理-月卡管理-查看详情
  {
    path: '/viewMonthCard',
    component: () => import('@/views/Car/CarCard/viewMonthCard.vue')
  }, // 行车管理-月卡管理-月卡续费
  {
    path: '/renewMonthCard',
    component: () => import('@/views/Car/CarCard/renewMonthCard.vue')
  }, // 一体感记录-告警记录-详情
  {
    path: '/warningDetail',
    component: () => import('@/views/Rod/RodWarn/detail.vue')
  }

]
// 动态路由表,需要权限控制访问的路由页面对象
export const asyncRoutes = [
  {
    path: '/park',
    component: Layout,
    permission: 'park',
    meta: { title: '园区管理', icon: 'el-icon-office-building' },
    children: [{
      path: 'building',
      permission: 'park:building',
      meta: { title: '楼宇管理' },
      component: () => import('@/views/Park/Building/index')
    },
    {
      path: 'enterprise',
      permission: 'park:enterprise',
      meta: { title: '企业管理' },
      component: () => import('@/views/Park/Enterprise/index')
    }]
  },

  {
    path: '/parking',
    component: Layout,
    permission: 'parking',
    meta: { title: '行车管理', icon: 'el-icon-guide' },
    children: [{
      path: 'area',
      permission: 'parking:area',
      component: () => import('@/views/Car/CarArea'),
      meta: { title: '区域管理' }
    }, {
      path: 'card',
      permission: 'parking:card',
      component: () => import('@/views/Car/CarCard'),
      meta: { title: '月卡管理' }
    }, {
      path: 'pay',
      permission: 'parking:payment',
      component: () => import('@/views/Car/CarPay'),
      meta: { title: '停车缴费管理' }
    },
    {
      path: 'rule',
      permission: 'parking:rule',
      component: () => import('@/views/Car/CarRule'),
      meta: { title: '计费规则管理' }
    }]
  },
  {
    path: '/pole',
    component: Layout,
    permission: 'pole',
    meta: { title: '一体杆管理', icon: 'el-icon-refrigerator' },
    children: [{
      path: 'info',
      permission: 'pole:info',
      component: () => import('@/views/Rod/RodManage'),
      meta: { title: '一体杆管理' }
    }, {
      path: 'waring',
      permission: 'pole:warning',
      component: () => import('@/views/Rod/RodWarn'),
      meta: { title: '告警记录' }
    }]
  },
  {
    path: '/sys',
    component: Layout,
    permission: 'sys',
    meta: { title: '系统管理', icon: 'el-icon-setting' },
    children: [{
      path: 'role',
      permission: 'sys:role',
      component: () => import('@/views/System/Role/index'),
      meta: { title: '角色管理' }
    }, {
      path: 'user',
      permission: 'sys:user',
      component: () => import('@/views/System/Employee/index'),
      meta: { title: '员工管理' }
    }]
  },
  {
    path: '/propety',
    component: Layout,
    permission: 'property',
    children: [{
      // 注意：这里路径字符串为空，代表一级菜单无二级菜单
      path: '',
      name: 'cost',
      permission: 'propertyFee',
      // 二级路由点，要挂载的组件
      component: () => import('@/views/Propety/index'),
      // 左侧路由上标题和图标（图标使用 element-ui 组件库里图标类名（因为左侧导航组件是基于 element-ui 组件库）
      meta: { title: '物业费管理', icon: 'el-icon-wallet' }
    }]
  }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: routes
})

const router = createRouter()

// 重置路由方法
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter()
  // 使用新的路由记录覆盖掉老的路由记录
  router.matcher = newRouter.matcher
}

router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  const whiteList = ['/login']
  if (token) {
    next()
    // 获取用户信息
    if (!store.state.user.profile.id) {
      const userRoutes = []
      // 获取原始权限列表
      // dispatch 原地是一个 Promise 对象,而值来自你调用的 actions 函数内 return 的结果
      // 没有 id 的情况,(它刚用网站修改了自己相关的信息清空,在下一次切换页面的时候获取)
      // 情况2:登录跳转到内容页面(第一次登录网站),进入获取一次当前用户的信息
      // 情况3:refresh_token 不重新登录,也能获取最新的 token,代码删除用户的信息
      // 下一次跳转页面时, id 无值, 就会带着新的 token 再去获取最新的用户信息

      // 1.获取原始权限列表
      const res = await store.dispatch('user/getProfile')
      // console.log(res)
      // 现在:后台给我返回的权限点标记是一个英文字符串数组['parking:rule:list','parking:rule:add_edit]
      // 2. 目标:得到['parking']
      const resultList = []
      res.data.permissions.forEach(item => {
        resultList.push(item.split(':')[0])
      })
      // 数组去重用集合
      // console.log(resultList)
      const firstPermissionList = Array.from(new Set(resultList))
      // console.log(FirstPermissionList)
      // 3. 目标：提取"二级"集合得到["parking:card"]
      let secondPerList = res.data.permissions.map(item => {
        // lastIndexOf 查找指定字符的下标(从末尾往前查)(下标从前往后)
        const lastInd = item.lastIndexOf(':')
        const targetStr = item.substring(0, lastInd)
        return targetStr
      })
      secondPerList = Array.from(new Set(secondPerList))
      // console.log(secondPerList)
      if (firstPermissionList[0] === '*') {
        // 管理员
        userRoutes.push(...routes) // 把筛选后的动态路由对象合并回到 routes 路由
        userRoutes.push(...asyncRoutes) // 把筛选后的动态路由对象合并回到 routes 路由
        const arr = [...asyncRoutes]
        arr.push({
          path: '*',
          component: () => import('@/views/404'),
          hidden: true
        })
        store.commit('user/setUserRouters', userRoutes) // 传递到vuex里
        arr.forEach(routeObj => {
          router.addRoute(routeObj)
        })
      } else {
        // 4. 动态路由数组和权限点匹配筛选
        const routerArr = asyncRoutes.filter(obj => {
          // 查看当前路由对象 permission 字段的值在权限点数组中就 return true
          // 让filter 把当前路由对象收集起来
          return firstPermissionList.includes(obj.permission)
        }).map(obj => {
          return { ...obj,
            children: obj.children.filter(sobj => secondPerList.includes(sobj.permission)) }
        })
        // console.log(routerArr)
        // 5.存store和传动态路由
        userRoutes.push(...routes) // 把筛选后的动态路由对象合并回到 routes 路由
        userRoutes.push(...routerArr) // 把筛选后的动态路由对象合并回到 routes 路由
        const arr = [...routerArr]
        arr.push({
          path: '*',
          component: () => import('@/views/404'),
          hidden: true
        })
        store.commit('user/setUserRouters', userRoutes) // 传递到vuex里
        // 问题: 点击筛选后的路由对象,跳转不了
        // 原因: Router 时 routes 只有静态的路由规则对象
        // 尝试: route 给我们一个 addRoute 方法可以动态追加可以"匹配"的路由对象
        arr.forEach(routeObj => {
          router.addRoute(routeObj)
        })
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
